#include<vector>
using namespace std;
class Solution {
public:
    int trap(vector<int>& height) {
        int res = 0;
        int left = 0, right = 0;
        int left_idx = 0, right_idx = height.size() - 1;
        while (left_idx <= right_idx) {
            if (left < right) {
                if (left < height[left_idx])
                    left = height[left_idx];
                else
                    res += left - height[left_idx];
                ++left_idx;
            }
            else {
                if (right < height[right_idx])
                    right = height[right_idx];
                else
                    res += right - height[right_idx];
                --right_idx;
            }
        }
        return res;
    }
};